package com.jl.core.controller;

import com.alibaba.fastjson.JSONObject;
import com.jl.api.CommonApi;
import com.jl.config.BaseResponse;
import com.jl.config.PageModel;
import com.jl.constants.ReturnCode;
import com.jl.core.model.resp.AccountStatistic;
import com.jl.core.model.resp.OperateRecordResp;
import com.jl.core.model.resp.QueryExchangeResp;
import com.jl.core.model.resp.StatisticResp;
import com.jl.core.netty.MyWebSocketHandler;
import com.jl.core.service.CoalitionService;
import com.jl.enums.GameType;
import com.jl.gongniu.model.dto.SzQueueInfo;
import com.jl.model.CoalitionRoomList;
import com.jl.model.socket.RoomDetail;
import com.jl.model.vo.CoalitionVo;
import com.jl.model.vo.UserVo;
import com.jl.service.GetUserInfoService;
import com.jl.service.RoomInfoService;
import com.jl.utils.CommonUtils;
import com.jl.utils.ObjectUtils;
import com.jl.utils.UserInfoContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
大联盟
 */
@RestController
@RequestMapping("coalition")
@Slf4j
@Api(description = "大联盟")
public class CoalitionController {

    @Autowired
    private CoalitionService coalitionService;

    @Autowired
    private ObjectUtils objectUtils;

    private String type;

    @Autowired
    private RoomInfoService roomInfoService;

    @GetMapping("getCoalitionList")
    @ApiOperation(value = "大联盟列表")
    public BaseResponse<List<CoalitionVo>> getCoalitionList(){
        List<CoalitionVo> list = coalitionService.getList();
        return BaseResponse.success(list);
    }

    @GetMapping("create")
    @ApiOperation(value = "创建大联盟")
    public BaseResponse create(String name){
        UserVo user = UserInfoContext.getUser();
        if (!GetUserInfoService.isManager()){ //非管理员
            return BaseResponse.error(ReturnCode.非管理员.getValue(),"非管理员无法创建");
        }
        coalitionService.create(name,user);
        return BaseResponse.success();
    }

    @GetMapping("getRoomList")
    @ApiOperation(value = "房间列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coalitionId", value = "大联盟ID",required = true, paramType = "query"),
            @ApiImplicitParam(name = "gameType", value = "游戏类型(1牛牛 2斗公牛 3炸金花,不传查所有)", paramType = "query")
    })
    public BaseResponse<List<CoalitionRoomList>> getRoomList(Integer coalitionId, String gameType,Integer roomId){
        List<CoalitionRoomList> roomList = coalitionService.getRoomList(coalitionId, gameType,roomId);
        return BaseResponse.success(roomList);
    }

    @GetMapping("getRoomDetail")
    @ApiOperation(value = "查询房间详情(用于编辑房间)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间id",required = true, paramType = "query"),
            @ApiImplicitParam(name = "gameType", value = "游戏类型(1牛牛 2斗公牛 3炸金花)",required = true,paramType = "query")
    })
    public BaseResponse getRoomDetail(Integer roomId, String gameType){
        CommonApi targetService = objectUtils.getTargetService(gameType);
        return BaseResponse.success(targetService.getRoomDetail(roomId));
    }

    @GetMapping("getParam")
    @ApiOperation(value = "获取参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "gameType", value = "游戏类型(1牛牛 2斗公牛 3炸金花)",required = true, paramType = "query")
    })
    public BaseResponse getParam(String gameType){
        type = gameType;
        CommonApi targetService = objectUtils.getTargetService(gameType);
        if (targetService==null){
            return BaseResponse.error("501","无法创建该游戏房间");
        }
        return BaseResponse.success(targetService.getParam());
    }

    @PostMapping("createRoom")
    @ApiOperation(value = "创建/编辑房间(如果Id不传则创建, 传Id则编辑)")
    public BaseResponse createRoom(@RequestBody Object param){
        String gameType = type;
        if (gameType==null){
            try {
                gameType = PropertyUtils.getProperty(param, "gameType").toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Object room = objectUtils.getTargetService(gameType).createRoom(param);
        return BaseResponse.success(room);
    }

    @GetMapping("recordQueue")
    @ApiOperation(value = "战绩查询")
    public BaseResponse recordQueue(String gameType){
//        coalitionService.recordQueue(gameType);
        return BaseResponse.success(objectUtils.getTargetService(gameType).recordQuery());

    }

    @GetMapping("review")
    @ApiOperation(value = "上局回顾")
    public BaseResponse review(Integer roomId,String gameType){
        return BaseResponse.success(objectUtils.getTargetService(gameType).review(roomId));
    }

    @GetMapping("getSocketMap")
    @ApiOperation(value = "map")
    public BaseResponse getSocketMap(Integer type,Integer roomId){
        switch (type){
            case 1:return BaseResponse.success(MyWebSocketHandler.niuRoomDetailMap.get(roomId));
            case 2:return BaseResponse.success(MyWebSocketHandler.gongNiuRoomDetailMap.get(roomId));
        }
        return BaseResponse.success();
    }

    @GetMapping("shuffleCard")
    @ApiOperation(value = "洗牌")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "游戏类型(1牛牛 2斗公牛 3炸金花)",required = true, paramType = "query")
    })
    public BaseResponse shuffleCard(Integer type,Integer roomId){
        String roomDetail = roomInfoService.getRoomDetail(roomId, type.toString());
        JSONObject jsonObject = JSONObject.parseObject(roomDetail);
        String advancedOptions = jsonObject.getString("advancedOptions");
        if (type.equals(GameType.type1.getId())){
            MyWebSocketHandler.niuRoomDetailMap.get(roomId).init(advancedOptions,GameType.type1);
        }else if (type.equals(GameType.type2.getId())){
            MyWebSocketHandler.niuRoomDetailMap.get(roomId).init(advancedOptions,GameType.type2);
        }
        return BaseResponse.success();
    }

    @GetMapping("cleanAnte")
    @ApiOperation(value = "清零锅底")
    public BaseResponse cleanAnte(Integer roomId){
        List<SzQueueInfo> szInfo = roomInfoService.getSzInfo(roomId, SzQueueInfo.class);
        for (SzQueueInfo szQueueInfo : szInfo) {
            if (szQueueInfo.getBanking().equals("1")){
                szQueueInfo.setAnte(new BigDecimal(0));
            }
        }
        roomInfoService.setSzInfo(roomId,szInfo);
        return BaseResponse.success();
    }

    @GetMapping("cleanRoom")
    @ApiOperation(value = "清空房间")
    public BaseResponse cleanRoom(Integer type ,Integer roomId){
        ConcurrentHashMap<Integer, RoomDetail> map = null;
        switch (type){
            case 1: map = MyWebSocketHandler.niuRoomDetailMap;break;

            case 2: map = MyWebSocketHandler.gongNiuRoomDetailMap;break;
        }
        map.remove(roomId);
        return BaseResponse.success();
    }

    @GetMapping("queryExchange")
    @ApiOperation(value = "兑换查询")
    public BaseResponse<QueryExchangeResp> queryExchange(){
        QueryExchangeResp queryExchangeResp = coalitionService.queryExchange();
        return BaseResponse.success(queryExchangeResp);
    }

    @GetMapping("bindBank")
    @ApiOperation(value = "绑定银行卡")
    public BaseResponse bindBank(String name,String bankNo,String bank){
        coalitionService.bindBank(name,bankNo,bank);
        return BaseResponse.success();
    }

    @GetMapping("exchange")
    @ApiOperation(value = "兑换")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rest", value = "剩余金币",required = true, paramType = "query")
    })
    public BaseResponse exchange(String coin,String bankNo,String rest){
        coalitionService.exchange(coin,bankNo,rest);
        return BaseResponse.success();
    }

    @GetMapping("bindAlipay")
    @ApiOperation(value = "绑定支付宝")
    public BaseResponse bindAlipay(String account){
        coalitionService.bindAlipay(account);
        return BaseResponse.success();
    }

    @GetMapping("give")
    @ApiOperation(value = "赠送(不需要登录密码)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "获赠人ID",required = true, paramType = "query"),
            @ApiImplicitParam(name = "coin", value = "赠送金额",required = true, paramType = "query")
    })
    public BaseResponse give(Integer userId,String coin){
        coalitionService.give(userId,coin);
        return BaseResponse.success();
    }

    @GetMapping("queryRecord")
    @ApiOperation(value = "查询记录")
    public BaseResponse<PageModel<OperateRecordResp>> queryRecord(@RequestParam(defaultValue = "1") Integer pageNumb,
                                                                  @RequestParam(defaultValue = "9") Integer pageSize){
        PageModel<OperateRecordResp> pageModel = coalitionService.queryRecord(pageNumb,pageSize);
        return BaseResponse.success(pageModel);
    }

    @GetMapping("recharge")
    @ApiOperation(value = "充值")
    public BaseResponse recharge(Integer userId,String coin){
        coalitionService.recharge(userId,coin);
        return BaseResponse.success();
    }

    @GetMapping("deleteRoom")
    @ApiOperation(value = "删除房间")
    public BaseResponse deleteRoom(){
        coalitionService.deleteRoom();
        return BaseResponse.success();
    }

    @GetMapping("statistic")
    @ApiOperation(value = "统计")
    public BaseResponse<StatisticResp> statistic(@RequestParam(defaultValue = "1") Integer pageNumb,
                                                 @RequestParam(defaultValue = "9") Integer pageSize,
                                                 String date){
        StatisticResp statistic = coalitionService.statistic(pageNumb, pageSize,date);
        return BaseResponse.success(statistic);
    }

    @GetMapping("notice")
    @ApiOperation(value = "公告")
    public BaseResponse notice(){
        String notice = coalitionService.notice();
        return BaseResponse.success(notice);
    }
}
